package com.web.base.auth.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.blue.jdbc.BaseDao;
import com.web.base.auth.model.Menu;

/**
 * 菜单数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年04月15日
 */
@Repository
public class MenuDao extends BaseDao<Menu>
{
	public MenuDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, Menu param)
	{
		if (param != null)
		{
			if (param.getParentId() != null && param.getParentId() > 0)
				sql.append(" and a.parent_id=:parentId");
				
			if (param.getAppId() != null && param.getAppId() > 0)
				sql.append(" and a.app_id=:appId");
				
			if (param.getName() != null && !param.getName().isEmpty())
			{
				sql.append(" and a.name like :name");
				param.setName("%" + param.getName() + "%");
			}
			
			if (param.getState() != null)
				sql.append(" and a.state=:state");
				
		}
		sql.append(" order by a.sort, a.id");
	}
	
	public List<Menu> listByUser(Integer userId)
	{
		Map<String, Object> param = new HashMap<>();
		param.put("userId", userId);
		String sql = "select * from auth_menu where state=0 and id in " +
				"(select menu_id from auth_role_menu where role_id in " +
				"(select ra.role_id from auth_role_user ra, auth_role r where ra.role_id=r.id and r.state=0 and ra.user_id=:userId)) order by sort asc";
		List<Menu> list = jdbcObjectTemplate.list(Menu.class, sql, param);
		return list;
	}
	
}
